package cn.edu.zut.internship.web.shiro;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class RedisCache implements Cache {
    @Autowired
    private RedisClusterCache redisClusterCache;


    private static final int EXPIRETIME = 3600*12;
    private static final String PREFIX = "internship:session:";

    /**
     * 从缓存获取Session对象
     * @param o
     * @return
     * @throws CacheException
     */
    @Override
    public Object get(Object o) throws CacheException {
        Object object = redisClusterCache.getCache(PREFIX + (String) o);
        return object;
    }

    /**
     * 将Session对象放入缓存
     * @param o
     * @param o2
     * @return
     * @throws CacheException
     */
    @Override
    public Object put(Object o, Object o2) throws CacheException {
        return redisClusterCache.putCacheWithExpireTime(PREFIX + o, o2, EXPIRETIME);
    }

    /**
     * 从移除Session对象
     * @param o
     * @return
     * @throws CacheException
     */
    @Override
    public Object remove(Object o) throws CacheException {
        Object value = redisClusterCache.getCache(PREFIX + o);
        redisClusterCache.delCache(PREFIX + o);
        return  value;
    }

    /**
     * 清空缓存所有Session对象
     * @throws CacheException
     */
    @Override
    public void clear() throws CacheException {
        redisClusterCache.delCache((Set<String>)keys());
    }

    /**
     * 获取缓存内所有Session对象的数量
     * @return
     */
    @Override
    public int size() {
        return keys().size();
    }

    /**
     * 获取缓存内所有Session对象的Key
     * @return
     */
    @Override
    public Set keys() {
        Set keys = redisClusterCache.keys(PREFIX + "*");
        return keys != null ? keys : Collections.emptySet();
    }

    /**
     * 获取缓存内所有的Session对象
     * @return
     */
    @Override
    public Collection values() {
        Set<String> keys = (Set<String>)keys();
        Collection c = new HashSet<>();
        for (String key : keys) {
            c.add( redisClusterCache.getCache(key));
        }
        return c;
    }

}

